package com.think.in.spring.ioc.overview.dependency.lookup;

import com.think.in.spring.ioc.overview.domain.Super;
import com.think.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;
import java.util.Map;

/**
 *
 * 依赖查找demo
 * @author : zjj
 * @date : 2021/12/28 9:10
 */
public class DependencyLookupDemo {
    public static void main(String[] args) {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("META-INF/dependency-lookup-context.xml");

        lookupInRealtime(beanFactory);
        lookupInLazy(beanFactory);

        lookupByType(beanFactory);

        lookupCollectionByType(beanFactory);

        lookupByAnnotationType(beanFactory);
    }

    /**
     * 通过注解类型来查找
     * @param beanFactory
     */
    private static void lookupByAnnotationType(BeanFactory beanFactory) {
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;

            Map<String,User> user = (Map)listableBeanFactory.getBeansWithAnnotation(Super.class);
            System.out.println(user);

        }

    }

    /**
     * 通过类型查找 集合
     * @param beanFactory
     */
    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> beansOfType = listableBeanFactory.getBeansOfType(User.class);

            System.out.println("类型查找 ，集合：" + beansOfType);

        }
    }

    /**
     * 通过类型实时查找
     * @param beanFactory
     */
    private static void lookupByType(BeanFactory beanFactory) {
        User bean = beanFactory.getBean(User.class);
        System.out.println("通过类型查找：" + bean);
    }

    /**
     * 实时获取
     * @param beanFactory
     */
    public static void lookupInRealtime(BeanFactory beanFactory){
        User user =(User) beanFactory.getBean("user");

        System.out.println("实时加载" + user);
    }

    /**
     * 延迟加载
     * @param beanFactory
     */
    public static void lookupInLazy(BeanFactory beanFactory){
        ObjectFactory objectFactory=(ObjectFactory) beanFactory.getBean("beanFactory");
        User user = (User)  objectFactory.getObject();

        System.out.println("延迟加载：" + user);
    }
}
